package com.yboot.module.system.auth.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import com.yboot.module.system.auth.model.dto.LoginDto;
import com.yboot.module.system.auth.model.vo.AccessTokenVo;
import com.yboot.module.system.auth.service.IAuthService;
import com.yboot.module.system.model.vo.SysMenuVo;
import com.yboot.module.system.model.vo.SysRoleVo;
import com.yboot.module.system.model.vo.menu.RouterVo;
import com.yboot.module.system.service.ISysMenuService;
import com.yboot.module.system.service.ISysRoleService;
import com.yboot.starter.common.core.userdetails.LoginUser;
import com.yboot.starter.common.core.web.vo.Result;
import com.yboot.starter.satoken.core.utils.SaTokenUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 登录接口
 * @author yangcs
 * @date 2025-08-29
 */
@RestController
@RequiredArgsConstructor
public class AuthController {

    private final IAuthService authService;
    private final ISysRoleService sysRoleService;
    private final ISysMenuService sysMenuService;

    /**
     * 登录
     */
    @SaIgnore
    @PostMapping("/login")
    public Result<AccessTokenVo> login(@Validated @RequestBody LoginDto loginDto) {
        loginDto.setAuthType("password");
        return Result.ok(authService.login(loginDto));
    }

    /**
     * 获取信息
     */
    @GetMapping("/getInfo")
    public Result<LoginUser> getInfo() {
        LoginUser user = SaTokenUtils.getUser();
        List<SysRoleVo> roleList = sysRoleService.getRoleList(user.getId());
        return Result.ok(user)
                .put("roles", roleList);
    }

    /**
     * 获取路由
     */
    @GetMapping("/getRouters")
    public Result<List<RouterVo>> getRouters() {
        List<SysMenuVo> menus = sysMenuService.getMenuTreeByUserId(SaTokenUtils.getUserId());
        List<RouterVo> tree = sysMenuService.buildMenus(menus);
        return Result.ok(tree);
    }


    /**
     * 登出
     */
    @SaIgnore
    @PostMapping("/logout")
    public Result logout() {
        StpUtil.logout();
        return Result.ok();
    }
}
